--[[
	处理使用道具
]]
local filename = "useprop.lua"

local timetool = require "timetool"
local skynet = require "skynet"
local cluster = require "skynet.cluster"
local filelog =require "filelog"
local redisdao = require "redisdao"
require "pubenum"

local json = require "cjson"
json.encode_sparse_array(true,1,1)


--道具类型
local PROP_TYPE = {
    FANGKA = 1,         --房卡
    DIAMOND = 2,        --金豆
    COIN = 3,           --金币
}


local service = nil
local CMD = {
	service = nil
}

local function get_prop_usetime(rid, propid)
    local cur_time = timetool.get_time()
    local all_prop_usetimes = nil
    local key = tostring(rid) .. ":prop_usetimes"
    local result, data = redisdao.query_data(".gmmqredis", "get", key)
    if result and data then
        all_prop_usetimes = json.decode(data)
    else
        all_prop_usetimes =  all_prop_usetimes or {}
    end
    if all_prop_usetimes[tostring(propid)] == nil then
        all_prop_usetimes[tostring(propid)] = {
            last_use_time = timetool.get_time(),
            today_use_times = 0,
            total_use_times = 0,
        }
        redisdao.query_data(".gmmqredis", "set", key, json.encode(all_prop_usetimes))
    else
        if all_prop_usetimes[tostring(propid)].last_use_time > 0 then
            local cur_day = os.date("%d",cur_time)
            local last_use_day = os.date("%d",all_prop_usetimes[tostring(propid)].last_use_time)
            if last_use_day ~= cur_day then
                all_prop_usetimes[tostring(propid)].today_use_times = 0
                redisdao.query_data(".gmmqredis", "set", key, json.encode(all_prop_usetimes))
            end
        end
    end
    return all_prop_usetimes[tostring(propid)]
end

--
--处理背包中使用道具：消耗型道具减少数量 装备型道具更改装备状态
--
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end

    if not rid or not msgbody.id then
        return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "道具id不能为空"}
    end
    --获得道具配置
    local curitem = skynet.call(".knapsack", "lua", "getpropconf", msgbody.id)
    if not curitem then
        return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "无效的参数"}
    end

    local status, propitem = skynet.pcall(skynet.call, ".knapsack", "lua", "getpropbyid", rid, msgbody.id)
    if not propitem then
        return { retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "没有这个道具"}
    end

    --更新背包数据
    local updatelist = { }
    local ntclientlist = {}
    local updateitem = { }
    local kid = math.floor(msgbody.id / 100)
    updateitem.id = propitem.id
    updateitem.state = propitem.state
    updateitem.value = propitem.value
    if kid == PropKind.VIPCARD then   --会员卡
        if not updateitem.value or updateitem.value <= 0 then
            return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "无效的参数"}
        end
        updateitem.value = updateitem.value - msgbody.value
        updateitem.state = nil
        table.insert(ntclientlist, { id = propitem.id, state = updateitem.state, value = propitem.value })
    elseif kid == PropKind.HEADFRAME then   --头像框
        if updateitem.state ~= 1 and updateitem.state ~= 2 then
            return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "无效的参数"}
        end
        ---updateitem.value = nil
        if propitem.value ~= -1 and propitem.value < timetool.get_time() then
            return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "头像框已过期"}
        end
        updateitem.state = 1
        updateitem.value = 0
        --使用头像框时，要将使用中的头像框卸下
        if updateitem.state == 1 and service.info.logoframe > 0 and service.info.logoframe ~= updateitem.id then
            local logstatus, proplog = skynet.pcall(skynet.call, ".knapsack", "lua", "getpropbyid", rid, service.info.logoframe)
            if proplog then
                local otheritem = { }
                otheritem.id = proplog.id
                otheritem.value = 0
                otheritem.state = 2
                table.insert(updatelist, otheritem)
                table.insert(ntclientlist, { id = proplog.id, state = otheritem.state, value = proplog.value })
            end
        end
        table.insert(ntclientlist, { id = propitem.id, state = updateitem.state, value = propitem.value })
    elseif kid == PropKind.GIFTSPACKAGE then
        if not updateitem.value or updateitem.value <= 0 then
            return {retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "无效的参数" }
        end
        ----判断使用次数是否超过上限
        local use_times_info = get_prop_usetime(rid, msgbody.id)
        if curitem.total_use_limit and curitem.day_use_limit then
            if curitem.total_use_limit > 0 then
                if use_times_info.total_use_times >= curitem.total_use_limit then
                    return { retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "超过总使用次数限制" }
                end
            end
            if curitem.day_use_limit > 0 then
                if use_times_info.today_use_times >= curitem.day_use_limit then
                    return { retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "超过今日使用次数限制" }
                end
            end
        end
        updateitem.value = updateitem.value - 1
        updateitem.state = nil
        table.insert(ntclientlist, { id = propitem.id, state = updateitem.state, value = updateitem.value })
        updateitem.value = -1
    end
    table.insert(updatelist, updateitem)
    local result, newupdatelist = skynet.call(".knapsack", "lua", "updateknapsack", rid, updatelist)
    if not result then
        return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "道具使用失败"}
    end

    --会员卡道具，使用后增加会员时长
    local is_changeinfo = false
    local notifymsg = { }
    local get_props = {}
    if kid == PropKind.VIPCARD then
        if curitem.effecttime == -1 then
            service.info.chesstimelimit = -1
        else
            service.info.chesstimelimit = (service.info.chesstimelimit or 0) + (curitem.effecttime * 24 * 3600)
        end
        if not service.info.level or service.info.level == 0 then
            service.info.level = 1  --固定1级VIP
            is_changeinfo = true
            notifymsg.level = service.info.level
        end
        local msgbody = {chesstimelimit = service.info.chesstimelimit, level = service.info.level}
        cluster.call("datanode", ".router", "update_rk", rid, "rs_info", 0, msgbody)
    elseif kid == PropKind.HEADFRAME then
        --头像框道具更改当前头像框id
        service.info.logoframe = propitem.id
        is_changeinfo = true
        notifymsg.logoframe = service.info.logoframe
        local msgbody = { logoframe = service.info.logoframe }
        cluster.call("datanode", ".router", "update_rk", rid, "rs_info", 0 , msgbody)
    elseif kid == PropKind.GIFTSPACKAGE then
        if curitem.getitemlist then
            local itemvalues = { }
            local cur_prop_nums  = {}
            for index, item in pairs(curitem.getitemlist) do
                if item.id == PROP_TYPE.FANGKA then
                    if itemvalues["fangka"] == nil then itemvalues["fangka"] = 0 end
                    itemvalues["fangka"] = itemvalues["fangka"]  + item.num
                    cur_prop_nums["fangka"] = service.money.fangka or 0
                elseif item.id == PROP_TYPE.DIAMOND then
                    if itemvalues["diamond"] == nil then itemvalues["diamond"] = 0 end
                    itemvalues["diamond"] = itemvalues["diamond"] + item.num
                    cur_prop_nums["diamond"] = service.money.diamond or 0
                elseif item.id == PROP_TYPE.COIN then
                    if itemvalues["coin"] == nil then itemvalues["coin"] = 0 end
                    itemvalues["coin"] = itemvalues["coin"] + item.num
                    cur_prop_nums["coin"] = service.money.coin or 0
                else
                    ----查看是否有这个道具配置
                    local willgetitem = skynet.call(".knapsack", "lua", "getpropconf", item.id)
                    if willgetitem then
                        service:charge_prop(item.id, item.num, { giftkey = tostring(msgbody.id) .. "_" .. tostring(rid) .. "_" .. tostring(timetool.get_time())}, "usegiftpackage")
                    end
                end
                table.insert(get_props, { id = item.id, value = item.num })
            end
            local setargs = service:change_money(itemvalues)
            if setargs then
                --记录日志
                local logstr = nil
                local comment = { }
                local now = timetool.get_time()
                comment.tradeid = skynet.call(".nodeuuid", "lua", "getuuid")
                comment.table_uuid = "usegiftnode" .. "_" .. 0 .. "_" .. 0 .. "_" .. now
                for prop_name, value in pairs(itemvalues) do
                    if prop_name == "fangka" then
                        logstr = string.format("%d,%d,%s,%d,%d,%d", EFangKaChange.USE_GIFTPACKAGE, rid, "usegift", value, cur_prop_nums["fangka"], service.money.fangka)
                        skynet.send(".fangkalog", "lua", "write", logstr)
                    elseif prop_name == "diamond" then
                        logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", EDiamondChange.USE_GIFTPACKAGE, rid, service.info.level, value, 0, 0, cur_prop_nums["diamond"], service.money.diamond, service.money.lock_diamond, comment.table_uuid, now, comment.tradeid)
                        skynet.send(".diamondlog", "lua", "write", logstr)
                        --在游戏内兑换，通知游戏节点
                        if service.gamenode ~= "" then
                            skynet.pcall(cluster.send, service.gamenode, ".router", "rid_change_diamond", rid, cur_prop_nums["diamond"], value, service.money.diamond)
                        end 
                    elseif prop_name == "coin" then
                        logstr = string.format("%d,%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s", ECoinChange.USE_GIFTPACKAGE, rid, service.info.level, value, 0, 0, cur_prop_nums["coin"], service.money.coin, service.money.lock_coin, comment.table_uuid, now, comment.tradeid)
                        skynet.send(".coinlog", "lua", "write", logstr)
                        --在游戏内兑换，通知游戏节点
                        if service.gamenode ~= "" then
                            skynet.pcall(cluster.send, service.gamenode, ".router", "rid_change_coin", rid, cur_prop_nums["coin"], value, service.money.coin)
                        end 
                    end
                end
            end
        end
    end
    --通知玩家，基本信息改变
    if is_changeinfo then
        notifymsg.rid = rid
        service:notify_client("changebaseinfoN",{baseinfo = notifymsg})
    end
    --通知玩家,背包信息改变
    local change_notice = { change_prop_listjson = json.encode(ntclientlist) }
    service:notify_client("changepropN", change_notice)
    local responsemsg = {
        id = msgbody.id,
        get_items_json = json.encode(get_props),
    }
    return responsemsg
end

return CMD
